const fs = require("fs");
const path = require("path");
const PDFDocument = require("pdfkit");
const sharp = require("sharp");

const baseDir = `E:/Download/AAA/AA`;
function listFilesInDirectory(directoryPath) {
  const files = [];
  function readDirectory(currentPath) {
    const items = fs.readdirSync(currentPath);
    for (const item of items) {
      const itemPath = path.join(currentPath, item);
      const stats = fs.statSync(itemPath);
      if (stats.isDirectory()) {
      } else if (item.endsWith("png")) {
        files.push(itemPath);
      }
    }
  }
  readDirectory(directoryPath);
  return files;
}
const files = listFilesInDirectory(baseDir);

async function imagesToPdf3(imagePaths, outputPdfPath) {
  const doc = new PDFDocument({ size: "A4" });
  for (const imagePath of imagePaths) {
    const imageBuffer = await sharp(imagePath).toBuffer();
    const { width, height } = await sharp(imageBuffer).metadata();
    const scaleToFitWidth = doc.page.width / width;
    const scaleToFitHeight = doc.page.height / height;
    const scaleFactor = Math.min(scaleToFitWidth, scaleToFitHeight);
    const scaledWidth = width * scaleFactor;
    const scaledHeight = height * scaleFactor;
    doc.addPage();
    doc.image(
      imageBuffer,
      (doc.page.width - scaledWidth) / 2,
      (doc.page.height - scaledHeight) / 2,
      { width: scaledWidth, height: scaledHeight }
    );
  }
  const writeStream = fs.createWriteStream(outputPdfPath);
  doc.pipe(writeStream);
  doc.end();
}

async function imagesToPdf(imagePaths, outputPdfPath) {
  let pageWidth, pageHeight;
  {
    const imageBuffer = await sharp(imagePaths[0]).toBuffer();
    const size = await sharp(imageBuffer).metadata();
    pageWidth = size.width;
    pageHeight = size.height;
  }
  const doc = new PDFDocument({
    size: [pageWidth, pageHeight],
    margins: { top: 0, bottom: 0, left: 0, right: 0 },
  });
  for (let index = 0; index < imagePaths.length; index++) {
    const imagePath = imagePaths[index];
    const imageBuffer = await sharp(imagePath).toBuffer();
    const { width, height } = await sharp(imageBuffer).metadata();
    doc.image(imageBuffer, 0, 0, { width, height });
    if (index < imagePaths.length - 1) {
      doc.addPage();
    }
  }
  const writeStream = fs.createWriteStream(outputPdfPath);
  doc.pipe(writeStream);
  doc.end();
}

const outputPdfPath = path.join(baseDir, "aa-output.pdf");
imagesToPdf(files, outputPdfPath).then(() => {
  console.log("PDF created successfully.");
});
